package com.tim.app.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.KeyboardChangeListener;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.EmptyView;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.callback.ReplyCallback;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.entry.Comment;
import com.tim.app.server.entry.Story;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.CommentResult;
import com.tim.app.server.result.PublishCommentResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.StoryDetailResult;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.ui.adapter.comment.CommentInfoAdapter;
import com.tim.app.ui.popup.StoryListPop;
import com.tim.app.ui.view.StoryHeadView;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;


/**
 * 故事详情页面
 */
public class StoryDetailActivity extends BaseActivity implements KeyboardChangeListener.KeyBoardListener, LoadMoreHandler {

    public static final String TAG = "StoryDetailActivity";

    private ImageButton ibBack;
    private TextView tvTitle;
    private RelativeLayout rlAvatarContainer;
    private RoundedImageView rivAvatar;
    private EditText etComment;
    private TextView tvPublish;

    private int pageNumber = 1;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvComment;

    private CommentInfoAdapter adapter;
    private List<Comment> dataList;

    private StoryHeadView headView;

    private Story story;
    private List<Story> storyList;
    private int index;

    private KeyboardChangeListener mKeyboardChangeListener;
    private boolean isFromPush;
    private View llBottomContainer;

    EmptyLayout emptyLayout;

    public static void start(Context context, ArrayList<Story> stories, int position, boolean isFromPush) {
        Intent intent = new Intent(context, StoryDetailActivity.class);
        intent.putParcelableArrayListExtra(AppKey.STORY, stories);
        intent.putExtra("position", position);
        intent.putExtra("isFromPush", isFromPush);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_story_detail;
    }


    @Override
    public void initView() {

        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvComment = (WrapRecyclerView) findViewById(R.id.wrvComment);
        wrvComment.setOverScrollMode(View.OVER_SCROLL_NEVER);

        emptyLayout = new EmptyLayout(this, load_more);
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_search);
        emptyLayout.setEmptyText("该内容已经被删除了", "");

        ibBack = (ImageButton) findViewById(R.id.ibBack);
        tvTitle = (TextView) findViewById(R.id.tvTitle);

        rlAvatarContainer = (RelativeLayout) findViewById(R.id.rlAvatarContainer);
        rivAvatar = (RoundedImageView) findViewById(R.id.rivAvatar);

        llBottomContainer = findViewById(R.id.llBottomContainer);
        etComment = (EditText) findViewById(R.id.etComment);
        tvPublish = (TextView) findViewById(R.id.tvPublish);
        tvPublish.setOnClickListener(this);
        ibBack.setOnClickListener(this);

        rlAvatarContainer.setOnClickListener(this);

        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);

        EmptyView emptyView = (EmptyView) LayoutInflater.from(this).inflate(R.layout.empty_layout, null);
        emptyView.setLayoutParams(new RecyclerView.LayoutParams(-1, (int) RT.getDensity() * 228));
        emptyView.setData(R.drawable.ic_empty_follow, "你还没发表过评论");
        wrvComment.setEmptyView(emptyView);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvComment.setLayoutManager(layoutManager);
        headView = (StoryHeadView) LayoutInflater.from(this).inflate(R.layout.story_head_view, wrvComment, false);

        wrvComment.addHeaderView(headView);

        storyList = getIntent().getParcelableArrayListExtra(AppKey.STORY);
        index = getIntent().getIntExtra("position", 0);
        isFromPush = getIntent().getBooleanExtra("isFromPush", false);
        story = storyList.get(index);

        dataList = new ArrayList<>();
        adapter = new CommentInfoAdapter(this, dataList, AppKey.TYPE_STORY, story.getId());
        wrvComment.setAdapter(adapter);

        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);

        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(etComment.getText().toString())) {
                    tvPublish.setEnabled(false);
                } else {
                    tvPublish.setEnabled(true);
                }
            }
        });

        etComment.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (!UserManager.ins().isLogin()) {
                        wrvComment.setFocusable(true);
                        wrvComment.requestFocus();
                        ViewGT.gotoLoginActivity(StoryDetailActivity.this);
                    }
                } else {// 此处为失去焦点时的处理内容

                }
            }
        });
        wrvComment.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                SoftKeyboardUtil.hideSoftKeyboard(etComment);
                return false;
            }
        });
        EventManager.ins().registListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().registListener(EventTag.GO_PREVIOUS, eventListener);
        EventManager.ins().registListener(EventTag.GO_NEXT, eventListener);
        EventManager.ins().registListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().registListener(EventTag.DO_CONTENT_DELETE, eventListener);
        EventManager.ins().registListener(EventTag.ON_COMMENT_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_SELECT_PEPLY, eventListener);
        EventManager.ins().registListener(EventTag.DO_SHOW_KEYBOARD, eventListener);
        EventManager.ins().registListener(EventTag.SHOW_PLAY_LIST, eventListener);
        EventManager.ins().registListener(EventTag.GO_INDEX, eventListener);
        EventManager.ins().registListener(EventTag.ON_PLAY_PROCESS_CHANGED, eventListener);
        EventManager.ins().registListener(EventTag.ON_PLAY, eventListener);
        EventManager.ins().registListener(EventTag.ON_PAUSE, eventListener);
        EventManager.ins().registListener(EventTag.ON_COMPLETE, eventListener);
        EventManager.ins().registListener(EventTag.ON_STOP, eventListener);
        EventManager.ins().registListener(EventTag.ON_CLICK_NEXT, eventListener);
        EventManager.ins().registListener(EventTag.ON_CLICK_PREVIOUS, eventListener);
        EventManager.ins().registListener(EventTag.SEND_CURRENT_STORY_PLAYING, eventListener);
        API_Statistics.ins().addDetailData(TAG, this, AppKey.TYPE_STORY, story.getId());
        wrvComment.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mDistance += dy;
                if (dy < 0) {
//                    llBottomContainer.setVisibility(View.GONE);
                } else {
                    if (mDistance < headView.getHeight() / 3) {
//                        llBottomContainer.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

        });
    }

    int mDistance = 0;

    @Override
    public void initData() {
        showLoadingDialog();
        UserManager.ins().addBrowserHistory(TAG, AppKey.TYPE_STORY, story.getId());
        API_Found.ins().getStoryDetail(TAG, story.getId(), detailCallBack);
        API_Found.ins().getCommentList(TAG, AppKey.NO_SORT, AppKey.TYPE_STORY, story.getId(), pageNumber, AppKey.PAGE_SIZE, refreshCallback);
        showUi();
    }

    private void showUi() {
        if (null != story.getUserMsg()) {
            if (!TextUtils.isEmpty(story.getUserMsg().getImage())) {
                BitmapLoader.ins().loadImage(story.getUserMsg().getImage(), rivAvatar);
            } else {
                BitmapLoader.ins().loadImage("", rivAvatar);
            }
            if (!TextUtils.isEmpty(story.getUserMsg().getName())) {
                tvTitle.setText(story.getUserMsg().getName());
            } else {
                tvTitle.setText("");
            }
        } else {
            tvTitle.setText("");
            BitmapLoader.ins().loadImage("", rivAvatar);
        }
        headView.setData(this, storyList, index);
    }

    /**
     * 发布评论
     *
     * @param commentContent
     */
    private void publishDynamicComment(String commentContent) {
        API_Found.ins().publishComment(TAG, UserManager.ins().getUserId(), AppKey.TYPE_STORY, story.getId(), commentContent, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                SoftKeyboardUtil.hideSoftKeyboard(etComment);
                tvPublish.setEnabled(true);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    API_Statistics.ins().addActionData(TAG, StoryDetailActivity.this, AppKey.TYPE_COMMENT);
                    PublishCommentResult result = new Gson().fromJson(resultValue, PublishCommentResult.class);
                    etComment.setText("");
                    Comment comment = result.getRes().getComment();
                    comment.setUserMsg(UserManager.ins().getLoginUser());
                    dataList.add(0, comment);
                    story.setCommentCount(story.getCommentCount() + 1);
                    if (dataList.size() > 0) {
                        load_more.loadMoreFinish(false, false);
                    }
                    headView.updateStoryCommentCount(story);
                    adapter.notifyDataSetChanged();
                    ToastUtil.showToast("发表成功！");
                } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                    ToastUtil.showToast("由于对方的设置，你不能评论此故事");
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    StringResponseCallback detailCallBack = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            hideLoadingDialog();
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                StoryDetailResult result = new Gson().fromJson(resultValue, StoryDetailResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getStory()) {
                    story = result.getRes().getStory();
                    storyList.set(index, story);
                    showUi();
                }
            } else if (errCode == ResponseResult.ResultStatus.DELETED) {
                emptyLayout.showEmpty();
                EmptyActivity.start(StoryDetailActivity.this);
                finish();
            } else {
//                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                CommentResult result = new Gson().fromJson(resultValue, CommentResult.class);

                if (null != result && null != result.getRes()) {
                    dataList.clear();
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist() && null != result.getRes().getArraylist().getResult()) {
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        dataList.addAll(result.getRes().getArraylist().getResult());
                    }
                    adapter.notifyDataSetChanged();
                    if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }

                    if (dataList.size() == 0) {
                        load_more.loadMoreFinish(true, false);
                    }
                } else {
                    load_more.loadMoreFinish(true, false);
                }

            } else {
                load_more.loadMoreFinish(false, false);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                CommentResult result = new Gson().fromJson(resultValue, CommentResult.class);

                if (null != result && null != result.getRes()) {
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist() && null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                    }
                    adapter.notifyDataSetChanged();
                    if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                } else {
                    load_more.loadMoreFinish(false, false);
                }

            } else {
                load_more.loadMoreFinish(false, false);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().removeListener(EventTag.GO_PREVIOUS, eventListener);
        EventManager.ins().removeListener(EventTag.GO_NEXT, eventListener);
        EventManager.ins().removeListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().removeListener(EventTag.DO_CONTENT_DELETE, eventListener);
        EventManager.ins().removeListener(EventTag.ON_COMMENT_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_SELECT_PEPLY, eventListener);
        EventManager.ins().removeListener(EventTag.DO_SHOW_KEYBOARD, eventListener);
        EventManager.ins().removeListener(EventTag.SHOW_PLAY_LIST, eventListener);
        EventManager.ins().removeListener(EventTag.GO_INDEX, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PLAY_PROCESS_CHANGED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PLAY, eventListener);
        EventManager.ins().removeListener(EventTag.ON_PAUSE, eventListener);
        EventManager.ins().removeListener(EventTag.ON_COMPLETE, eventListener);
        EventManager.ins().removeListener(EventTag.ON_STOP, eventListener);
        EventManager.ins().removeListener(EventTag.ON_CLICK_NEXT, eventListener);
        EventManager.ins().removeListener(EventTag.ON_CLICK_PREVIOUS, eventListener);
        EventManager.ins().removeListener(EventTag.SEND_CURRENT_STORY_PLAYING, eventListener);
        OkHttpUtils.getInstance().cancelTag(TAG);
        OkHttpUtils.getInstance().cancelTag(CommentInfoAdapter.TAG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (isFromPush) {
            ViewGT.gotoMainActivity(StoryDetailActivity.this);
        }
    }

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        if (isShow) {

        } else {
            if (isReply) {
                isReply = false;
                adapter.setReplyComment(null, -1);
                etComment.setText("");
                etComment.setHint(getString(R.string.commentPrompt));
            }
        }
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.SHOW_PLAY_LIST:
                    StoryListPop storyListPop = new StoryListPop(StoryDetailActivity.this, storyList, index);
                    storyListPop.show(getWindow().getDecorView());
                    break;
                case EventTag.ACCOUNT_UPDATE_INFO:
                    initData();
                    break;
                case EventTag.ON_CLICK_PREVIOUS:
                    if (index == 0) {
                        ToastUtil.showToast("没有上一个了");
                        return;
                    }
                    headView.reset();
                    index = index - 1;
                    story = storyList.get(index);
                    initData();
                    EventManager.ins().sendEvent(EventTag.GO_PREVIOUS, 0, 0, null);
                    break;
                case EventTag.GO_INDEX:
                    int newIndex = (int) dataobj;
                    if (newIndex != index) {
                        headView.reset();
                        index = newIndex;
                        story = storyList.get(newIndex);
                        initData();
                    }
                    break;
                case EventTag.ON_CLICK_NEXT:
                    if (index == storyList.size() - 1) {
                        ToastUtil.showToast("没有下一个了");
                        return;
                    } else {
                        index = index + 1;
                    }
                    headView.reset();
                    story = storyList.get(index);
                    initData();
                    EventManager.ins().sendEvent(EventTag.GO_NEXT, 0, 0, null);
                    break;
                case EventTag.DO_REPORT:
                    if (UserManager.ins().isLogin()) {
                        UserManager.ins().report(TAG, AppKey.TYPE_STORY, story.getId());
                    } else {
                        ViewGT.gotoLoginActivity(StoryDetailActivity.this);
                    }
                    break;
                case EventTag.DO_CONTENT_DELETE:
                    deleteMyStory();
                    break;
                case EventTag.ON_COMMENT_DELETED://评论删除
                    int position = (int) dataobj;
                    if (dataList.size() > position) {
                        dataList.remove(position);
                        adapter.notifyDataSetChanged();
                        story.setCommentCount(story.getCommentCount() - 1);
                        headView.updateStoryCommentCount(story);
                    }
                    break;
                case EventTag.ON_SELECT_PEPLY://选中评论
                    String typeId = String.valueOf(arg1);
                    Comment selectComment = (Comment) dataobj;
                    if (typeId.equals(story.getId())) {
                        etComment.setHint(getString(R.string.replySomeone, selectComment.getUserMsg().getName()));
                        isReply = true;
                    }
                    etComment.setFocusable(true);
                    etComment.requestFocus();
                    SoftKeyboardUtil.showSoftKeyboard(etComment);
                    break;
                case EventTag.DO_SHOW_KEYBOARD:
                    etComment.requestFocus();
                    SoftKeyboardUtil.showSoftKeyboard(etComment);
                    break;
                case EventTag.ON_PLAY_PROCESS_CHANGED:
                    int current = arg1;
                    int total = arg2;
                    headView.updateProcessAndTime(current, total);
                    break;
                case EventTag.ON_PLAY:
                    headView.onPlay();
                    break;
                case EventTag.ON_PAUSE:
                    headView.onPause();
                    break;
                case EventTag.ON_COMPLETE:
                    headView.onComplete();
                    break;
                case EventTag.ON_STOP:
                    headView.onStop();
                    break;
                case EventTag.SEND_CURRENT_STORY_PLAYING:
                    Story currentPlayingStory = (Story) dataobj;
                    if (null != story && null != currentPlayingStory && currentPlayingStory.getId().equals(story.getId())) {
                        headView.onPlay();
                    }
                    break;
            }

        }
    };

    boolean isReply = false;

    /**
     * 删除我的故事
     */
    private void deleteMyStory() {
        API_Found.ins().deleteMyStory(TAG, story.getId(), new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK) {
                    ToastUtil.showToast("删除成功");
                    EventManager.ins().sendEvent(EventTag.ON_STORY_DELETED, 0, 0, story.getId());
                    finish();
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                finish();
                break;
            case R.id.tvPublish://发布
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(this);
                    return;
                }
                String content = etComment.getText().toString();
                if (isReply) {
                    adapter.postReplyComment(content, new ReplyCallback() {
                        @Override
                        public void onSuccess() {
                            story.setCommentCount(story.getCommentCount() + 1);
                            headView.updateStoryCommentCount(story);
                            etComment.setText("");
                            etComment.setHint(getString(R.string.commentPrompt));
                            SoftKeyboardUtil.hideSoftKeyboard(etComment);
                        }

                        @Override
                        public void onFail() {
                            ToastUtil.showToast("发布失败，请稍后再试");
                        }
                    });
                } else {
                    publishDynamicComment(content);
                }
                break;
            case R.id.rlAvatarContainer:
                SoftKeyboardUtil.hideSoftKeyboard(etComment);
                if (null != story && null != story.getUserMsg()) {
                    SomeoneHomepageActivity.start(this, story.getUserMsg(), false);
                }
                break;
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Found.ins().getCommentList(TAG, AppKey.NO_SORT, AppKey.TYPE_DYNAMIC, story.getId(), pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
    }
}
